#include "Map.h"
#include <iostream>

using namespace std;


CMap::CMap() : m_uiNbTilesX(0),
		m_uiNbTilesY(0)
{}

CMap::~CMap()
{
	resetMap();
}

void CMap::init(unsigned int uiNbTileX, unsigned int uiNbTileY)
{
	resetMap();
	const unsigned int ui_sizemap = uiNbTileX * uiNbTileY;
	m_uiNbTilesX = uiNbTileX;
	m_uiNbTilesY = uiNbTileY;

	for (unsigned int i = 0; i < ui_sizemap; ++i)
	{
		MapTilePtr pTile( new CMapTile() );
		m_pTiles.push_back( pTile );
	}
}

void CMap::render()
{
	cout << "Render map." << endl;
	for_each( m_pTiles.begin(), m_pTiles.end(), MapTilePtrRender() );
}

void CMap::update()
{
	cout << "Update map." << endl;
}


void CMap::resetMap()
{
	for (std::vector<MapTilePtr>::iterator ite = m_pTiles.begin();
		ite != m_pTiles.end(); ++ite)
	{
		(*ite).reset();
	}
	m_pTiles.clear();
	m_uiNbTilesX = 0;
	m_uiNbTilesY = 0;
}



void CMap::load(const MazePtr& pContent)
{
	init(pContent->getSizeX() * 3, pContent->getSizeY() * 3);
	
	unsigned int m = 1;
	unsigned int n = 1;
	for (unsigned int j = 0; j < pContent->getSizeX(); ++j)
	{
		for (unsigned int i = 0; i <pContent->getSizeX(); ++i)
		{
			CMapTile::eType typN = ((pContent->getCell(i, j)->m_flags & SMazeCell::WallNorth)? CMapTile::wall : CMapTile::floor);
			CMapTile::eType typE = ((pContent->getCell(i, j)->m_flags & SMazeCell::WallEast)?  CMapTile::wall : CMapTile::floor);
			CMapTile::eType typS = ((pContent->getCell(i, j)->m_flags & SMazeCell::WallSouth)? CMapTile::wall : CMapTile::floor);
			CMapTile::eType typW = ((pContent->getCell(i, j)->m_flags & SMazeCell::WallWest)?  CMapTile::wall : CMapTile::floor);

			m_pTiles[(m - 1) * m_uiNbTilesX + (n - 1)]->setType(CMapTile::wall);
			m_pTiles[(m - 1) * m_uiNbTilesX + (n    )]->setType(typN);
			m_pTiles[(m - 1) * m_uiNbTilesX + (n + 1)]->setType(CMapTile::wall);

			m_pTiles[(m    ) * m_uiNbTilesX + (n - 1)]->setType(typW);
			m_pTiles[(m    ) * m_uiNbTilesX + (n    )]->setType(CMapTile::floor);
			m_pTiles[(m    ) * m_uiNbTilesX + (n + 1)]->setType(typE);

			m_pTiles[(m + 1) * m_uiNbTilesX + (n - 1)]->setType(CMapTile::wall);
			m_pTiles[(m + 1) * m_uiNbTilesX + (n    )]->setType(typS);
			m_pTiles[(m + 1) * m_uiNbTilesX + (n + 1)]->setType(CMapTile::wall);
		}
	}
}